package com.lurencun.android.topicbank.util;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * @brief 工具类，包括：封装JSON、解析JSON等
 * @author xiaoyu.wang
 * @date 2012-12-3
 * @version 1.0.0
 * 
 *          Revision History - 2012-12-3: create
 * @param <T>
 ****************************************************************************************/
public class GsonUtil {

	private static GsonBuilder builder = new GsonBuilder();
	private static Gson gson;
	private static GsonUtil instance;

	public static GsonUtil getInstance() {
		if (instance == null) {
			instance = new GsonUtil();
			// 不转换没有 @Expose 注解的字段
//			builder.excludeFieldsWithoutExposeAnnotation();
			//Json中的日期表达方式没有办法直接转换成我们的Date类型, 因此需要单独注册一个Date的反序列化类.
			DateDeserializer ds = new DateDeserializer();
			//给GsonBuilder方法单独指定Date类型的反序列化方法
			builder.registerTypeAdapter(Date.class, ds);
			gson = builder.create();
		}
		return instance;
	}

	public <T> List<T> stl(String json, Type type) {
		return gson.fromJson(json, type);
	}
	
	public String mts(Map<String, Object> map) throws Exception {
		return gson.toJson(map);
	}

	public Map<String, Object> stm(String json) throws Exception {
		return gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
	}
	
	public Gson getGson() {
		return gson;
	}

	public String otj(Object object) {
		return gson.toJson(object);
	}
}
